import Blender
import sys
import decimal
import os

def export():
  objs = Blender.Object.Get()
  print objs

  filename = Blender.Get('filename')+'.se'

  #split path/filename:
  li = os.path.split(filename)

  #do a join
  filename = os.path.join(li[0], li[1])

  fp = open(filename, 'w')
  fp.write("<level>\n")

  Blender.Set('curframe', 0)
  for ob in objs:
    fp.write("\t<object type=\""+ob.type+"\" name=\"" + ob.name + "\">\n")


    fp.write("\t\t<position x=\"%f\" "  % ob.LocX)
    fp.write("y=\"%f\" " %  ob.LocY)
    fp.write("z=\"%f\"/>\n" % ob.LocZ)

    fp.write("\t\t<rotation x=\"%f\" " % ob.RotX)
    fp.write("y=\"%f\" " % ob.RotY)
    fp.write("z=\"%f\"/>\n" % ob.RotZ)

    fp.write("\t\t<scale x=\"%f\" " % ob.SizeX)
    fp.write("y=\"%f\" " % ob.SizeY)
    fp.write("z=\"%f\"/>\n" % ob.SizeZ)

    dump(ob, fp) 

    fp.write("\t</object>\n\n")

  fp.write("</level>\n")

def dump(obj, fp):
  if obj.type in ["Camera", "Lamp"]:
    return

  mesh = obj.getData(False, True)
  mesh.quadToTriangle()
  
  faces = mesh.faces
  verts = mesh.verts

  #Each Vertices:
  for v in verts:
    x = "%f" % v.co.x
    y = "%f" % v.co.y
    z = "%f" % v.co.z
    i = str(v.index)
    fp.write("\t\t\t<vertex id=\""+ i +"\" x=\""+x+"\" y=\""+y+"\" z=\""+z+"\"/>\n")
 
  fp.write("\n")
  for f in faces:
    a, b, c = str(f.verts[0].index), str(f.verts[1].index), str(f.verts[2].index)
    d, e, f = "%f" % f.no.x, "%f" % f.no.y, "%f" % f.no.z
    fp.write("\t\t\t<face id1=\""+a+"\" id2=\""+b+"\" id3=\""+c+"\" nox=\""+d+"\" noy=\""+e+"\" noz=\""+f+"\"/>\n")

#decimal.getcontext().prec = 12
export()
